import math

import cv2
import numpy
import numpy as np
from PIL import ImageFont, ImageDraw, Image


def get_center_point(point):
    cx = 0
    cy = 0
    for i in point:
      cx = cx+i[0]
      cy = cy+i[1]
    x = int(cx/4.0)
    y = int(cy/4.0)
    return [x, y]



def process_bar(percent, start_str='', end_str='', total_length=0):
    bar = ''.join(["\033[31m%s\033[0m"%'   '] * int(percent * total_length)) + ''
    bar = '\r' + start_str + bar.ljust(total_length) + ' {:0>4.1f}%|'.format(percent*100) + end_str
    print(bar, end='', flush=True)

def area(point):
    return distance(point[0],point[1])*distance(point[1],point[2])
def cv2ImgAddText(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, numpy.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        "font/simsun.ttc", textSize, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, textColor, font=fontStyle)
    # 转换回OpenCV格式
    return cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)


def rotate(ps, m):
    pts = np.float32(ps).reshape([-1, 2])  # 要映射的点
    pts = np.hstack([pts, np.ones([len(pts), 1])]).T
    target_point = np.dot(m, pts)
    target_point = [[int(target_point[0][x]),int(target_point[1][x])] for x in range(len(target_point[0]))]
    return target_point

def rotate_img_and_point(img,points,angle,center_x,center_y,resize_rate=1.0):
    h, w, c = img.shape
    M = cv2.getRotationMatrix2D((center_x,center_y), angle, resize_rate)
    res_img = cv2.warpAffine(img, M, (w, h))
    out_points = rotate(points, M)
    return res_img, out_points

def rotate_img(img,angle,resize_rate=1.0):
    h, w, c = img.shape
    center_x = int(w/2.0)
    center_y = int(h/2.0)
    M = cv2.getRotationMatrix2D((center_x, center_y), angle, resize_rate)
    res_img = cv2.warpAffine(img, M, (w, h))
    return res_img

def distance(x,y):
    return  math.sqrt((x[0]-y[0])**2+(x[1]-y[1])**2)

def get_center(p1,p2,p3,p4):
    cx = int((p1[0]+p2[0]+p3[0]+p4[0])/4.0)
    cy = int((p1[1]+p2[1]+p3[1]+p4[1])/4.0)
    return [cx, cy]

def get_w_h(point):
    return int(abs(point[1][0]-point[0][0])),int(abs(point[2][1]-point[1][1]))